package com.googlecode.gwtbb.client.only.widget.form.user;

import com.googlecode.gwtbb.client.only.remote.ClientSession;
import com.googlecode.gwtbb.client.only.remote.user.UserServiceProxy;
import com.googlecode.gwtbb.client.only.widget.form.FormWidget;
import com.googlecode.gwtbb.client.only.widget.form.entry.FormEntry;
import com.googlecode.gwtbb.client.shared.entity.user.User;
import com.googlecode.gwtbb.client.shared.remote.user.LoginUserBean;
import com.googlecode.gwtbb.client.shared.validation.Failure;
import com.googlecode.gwtbb.client.shared.validation.FieldId;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Abraham Grief
 * @version $Id$
 * @since Jun 26, 2008
 */
public class LoginForm extends FormWidget {
	private LoginUserBean loginUserBean = new LoginUserBean();

	public LoginForm(ClientSession session) {
		super(session);
		init();
	}

	public List<FormEntry> getFormEntries() {
		List<FormEntry> retVal = new ArrayList<FormEntry>(2);
		retVal.add(createLabeledTextBoxFormEntry(User.USERNAME, 0, null, 0, 0, cmss.fieldLabelUsername()));
		retVal.add(createLabeledPasswordTextBoxFormEntry(User.PASSWORD, 0, null, 1, 0, cmss.fieldLabelPassword()));
		return retVal;
	}

	public String getProcessName() {
		return "login";
	}

	public String getProcessSuccess() {
		return cmss.loginProcessSuccess();
	}

	public String getProcessTitle() {
		return cmss.loginProcessTitle();
	}

	public Map<FieldId, Failure> validate(Map<FieldId, Failure> failures, int index) {
		loginUserBean.setUsername(getValue(User.USERNAME, 0));
		loginUserBean.setPassword(getValue(User.PASSWORD, 0));
		loginUserBean.validate(failures, index);
		setValue(User.USERNAME, 0, loginUserBean.getUsername());
		setValue(User.PASSWORD, 0, loginUserBean.getPassword());
		return failures;
	}

	protected void doAction() {
		UserServiceProxy.instance().login(loginUserBean, asyncCallback);
	}
}
